// 到家购物车
var app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
Component({
  properties: {
    list: {
      type: Object
    },
    addressInfo: {
      type: Array
    },
    location: {
      type: String
    },
    pagelevel: {
      type: String
    }
  },
  /**
   * 组件的初始数据
   */
  data: {
    sendtime: '最快1小时送达',
    totalPrice: null,
    selectedAddr: false,
    accountlist: [],
    isEmpty: false,
    startX: "",
    moveX: "",
    showDelPop: false,
    curStoreId: '',
    curGoodId: "",
    curClassId: "",
    curGoodsIndex: "",
    curGoodsName: "",
    curGoodsPrice: "",
    curGoodsNum: "",
    deleteType: "", //删除类型，0为删除单个，1为整店删除
    showStores: false,
    keyword: "",
    isAccountCart: false
  },
  methods: {
    //操作刷新购物车
    getNewCart(goods) {
      goods[0].lackNum = 0;
      goods[0].selectedNum = 0;
      if (goods[0].list.length == 0) {
        goods[0].total_goods_amount = 0;
        goods[0].list = [];
      } else {
        for (var j = 0; j < goods[0].list.length; j++) {
          goods[0].list[j].isCanAdd = true;
          goods[0].list[j].isCanReduce = true;
          if (goods[0].list[j].is_selected == "1") {
            goods[0].selectedNum++;
          }
          if (goods[0].list[j].is_lack == 1) {
            goods[0].lackNum++;
          }
        }
        if (goods[0].selectedNum == goods[0].list.length) {
          goods[0].isSelectAll = true;
        } else {
          goods[0].isSelectAll = false;
        }
        if (goods[0].lackNum == goods[0].list.length) {
          goods[0].showSelectAll = false;
        } else {
          goods[0].showSelectAll = true;

        }
      }
      this.data.curStore = goods[0].store_id;
      this.data.curRecommendStoreId = goods[0].service_store_id>0&&goods[0].service_type=='entity'?goods[0].service_store_id:goods[0].store_id;
      this.setData({
        list: goods[0]
      })
    },
    // 商品数量增加
    addCount(e) {
      var curtarget = e.currentTarget.dataset;
      var price = curtarget.price,
        storeid = curtarget.storeid,
        goodsid = curtarget.id,
        index = curtarget.index,
        quantity = curtarget.num,
        name = curtarget.name,
        classid = curtarget.classid;
      this.data.curGoodsIndex = index;
      this.data.curClassId = classid;
      this.data.curStoreId = storeid;
      this.data.curGoodId = goodsid;
      this.setData({
        ['list.list[' + index + '].isCanAdd']: false
      })
      server.postJSON(common.storePath + 'cart/increase/', {
        "store_id": storeid,
        "goods_id": goodsid,
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude
      }, res => {
        if (res.data.errno == "0") {
          common.showErrorToast('添加成功');
          //埋点加入购物车
          wx.reportAnalytics('addgoods_bycart', {
            goodsname: name,
            addgoodsnum: parseInt(quantity) + 1,
            removegoodsnum: '',
            curgoodsnum: quantity,
            goodsprice: price,
          });
          this.storageUpdateGoods(storeid, goodsid, parseInt(quantity) + 1, classid);
          var goods = res.data.data;
          this.getNewCart(goods);
          if (!app.globalData.isAccount) {//判断非结算页返回操作不刷新
            app.globalData.refreshTag = false;
          }
        } else {
          this.setData({
            ['list.list[' + index + '].isCanAdd']: true
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    },
    //商品减1
    reduceCount(e) {
      var target = e.currentTarget.dataset
      var storeid = target.storeid,
        goodsid = target.id,
        index = target.index,
        classid = target.classid,
        quantity = target.num,
        name = target.name,
        price = target.price;
      this.data.curGoodsIndex = index;
      this.data.curClassId = classid;
      this.data.curStoreId = storeid;
      this.data.curGoodId = goodsid;
      this.data.deleteType = 0;
      this.setData({
        ['list.list[' + index + '].isCanReduce']: false
      })
      if (parseInt(target.num) > 1) {
        server.postJSON(common.storePath + 'cart/decrease/', {
          "store_id": storeid,
          "goods_id": goodsid,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude
        }, res => {
          if (res.data.errno == "0") {
            wx.reportAnalytics('addgoods_bycart', {
              goodsname: name,
              addgoodsnum: '',
              removegoodsnum: parseInt(quantity) - 1,
              curgoodsnum: quantity,
              goodsprice: price,
            });
            this.storageUpdateGoods(storeid, goodsid, parseInt(quantity) - 1, classid);
            var goods = res.data.data;
            this.getNewCart(goods);
            this.setData({
              ['list.list[' + index + '].isCanReduce']: true
            })
            if (!app.globalData.isAccount) {
              app.globalData.refreshTag = false;
            }
          } else {
            this.setData({
              ['list.list[' + index + '].isCanReduce']: true
            })
            common.showErrorToast(res.data.errmsg);
          }
        })
      } else {
        this.setData({
          showDelPop: true
        })
      }
    },
    //长按删除商品
    deleteCurGoods(e) {
      var target = e.currentTarget.dataset
      var storeid = target.storeid,
        goodsid = target.id,
        index = target.index,
        classid = target.classid,
        quantity = target.num,
        name = target.name,
        price = target.price;
      this.data.curGoodsIndex = index;
      this.data.curClassId = classid;
      this.data.curStoreId = storeid;
      this.data.curGoodId = goodsid;
      this.data.curGoodsName = name;
      this.data.curGoodsPrice = price;
      this.data.curGoodsNum = quantity;
      this.data.deleteType = 0;
      this.setData({
        ['list.list[' + index + '].isCanReduce']: false,
        showDelPop: true
      })
    },
    confirmDel() {
      if (this.data.deleteType == 0) {
        this.setData({
          ['list.list[' + this.data.curGoodsIndex + '].isCanReduce']: true
        })
        var param = {
          "goods": [{
            "store_id": this.data.curStoreId,
            "goods_id": this.data.curGoodId
          }],
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude
        }
        this.deleteGoods(param, this.data.curClassId);
      } else {
        var param = {
          "store_id": this.data.curStoreId,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude
        }
        server.postJSON(common.storePath + 'cart/deletegoods/', param, res => {
          if (res.data.errno == "0") {
            this.setData({
              showDelPop: false
            })
            this.getNewCart(res.data.data)
            if (this.data.curStoreId == this.data.curStore) {
              app.globalData.isDeleteByStore = true;
              if (!app.globalData.isAccount) {
                app.globalData.refreshTag = false;
              }
              wx.getStorage({
                key: 'updateStoreArry',
                success: res => {
                  wx.removeStorageSync('updateStoreArry')
                }
              })
            }
          } else {
            common.showErrorToast(res.data.errmsg);
          }
        })
      }

    },
    cancelDel() {
      this.setData({
        showDelPop: false
      })
      if (this.data.deleteType == 0) {
        this.setData({
          ['list.list[' + this.data.curGoodsIndex + '].isCanReduce']: true
        })
      }
    },
    //删除商品
    deleteGoods(param, classid) {
      server.postJSON(common.storePath + 'cart/deletegoods/', param, res => {
        if (res.data.errno == "0") {
          wx.reportAnalytics('addgoods_bycart', {
            goodsname: this.data.curGoodsName,
            addgoodsnum: '',
            removegoodsnum: 0,
            curgoodsnum: this.data.curGoodsNum,
            goodsprice: this.data.curGoodsPrice,
          });
          this.getNewCart(res.data.data);
          if (!app.globalData.isAccount) {
            app.globalData.refreshTag = false;
          }
          this.setData({
            showDelPop: false
          })
          var storeid = param.goods[0].store_id,
            goodsid = param.goods[0].goods_id;
          this.storageUpdateGoods(storeid, goodsid, 0, classid)
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    },
    //整店一键删除
    deleteByStore(e) {
      this.setData({
        curStoreId: e.currentTarget.dataset.storeid,
        deleteType: 1,
        showDelPop: true
      })
    },
    //全选
    selectAll(e) {
      var storeid = e.currentTarget.dataset.storeid,
        selectStatus = e.currentTarget.dataset.selectstatus;
      var param = {
        "store_id": storeid,
        "is_selected": "",
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude
      }
      if (selectStatus) {
        var newSelectStatus = "0";
        param.is_selected = newSelectStatus;
        this.changeSelect(param)
      } else {
        var newSelectStatus = "1";
        param.is_selected = newSelectStatus;
        this.changeSelect(param)
      }
    },
    //更改选择状态
    changeSelect(param) {
      server.postJSON(common.storePath + 'cart/select/', param, res => {
        if (res.data.errno == '0') {
          if (res.data.errmsg != "") {
            common.showErrorToast(res.data.errmsg);
          }
          this.getNewCart(res.data.data)
        } else {
          common.showErrorToast(res.data.errmsg);
        }
      })
    },
    //商品单选
    selectSingle(e) {
      var selectStatus = e.currentTarget.dataset.status,
        goods_id = e.currentTarget.dataset.id,
        storeid = e.currentTarget.dataset.storeid;
      if (selectStatus == 0) {
        var newSelectStatus = "1";
        var param = {
          "store_id": storeid,
          "goods_id": goods_id,
          "is_selected": newSelectStatus,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude
        }
        this.changeSelect(param)
      } else {
        var newSelectStatus = "0";
        var param = {
          "store_id": storeid,
          "goods_id": goods_id,
          "is_selected": newSelectStatus,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude
        }
        this.changeSelect(param)
      }
    },
    // 显示地址选择遮罩层
    showModal() {
      wx.navigateTo({
        url: '../common/addrListsByCity?fromtype=1&&frompage=cart',
      })
    },
    //结算商品
    formSubmit(e) {
      this.setData({
        isAccountCart: true
      })
      wx.login({
        success: resp => {
          wx.getUserInfo({
            success: res => {
              this.setData({
                showLoginPop: false
              })
              var code = resp.code,
                that = this,
                userParams = {
                  "js_code": code,
                  "encryptedData": res.encryptedData,
                  "iv": res.iv,
                  "userinfo": res.userInfo,
                  "longitude": app.globalData.locateLongitude,
                  "latitude": app.globalData.locateLatitude,
                  "province": app.globalData.locateProvince,
                  "city": app.globalData.locateCity,
                  "scene": ''
                };
              server.login(common.basePath + 'miniprogram/login/', userParams, function (res) {
                if (res.data.errno == "0") {
                  wx.setStorage({
                    key: "sso",
                    data: res.data.data.sso,
                    success: ret => {
                      if (JSON.stringify(res.data.data.member) == "{}") {
                        that.setData({
                          showPhonePop: true
                        })
                      } else if (JSON.stringify(res.data.data.member) != "{}") {
                        that.setData({
                          showPhonePop: false
                        })
                        that.data.accountlist = [];
                        let storeId = e.currentTarget.dataset.storeid,
                          tatalPrice = e.currentTarget.dataset.account;
                        let cart = that.data.list;
                        let storeList = cart.list;
                        for (var i = 0; i < storeList.length; i++) {
                          if (storeList[i].is_selected == 1 && storeList[i].is_lack == 0) {
                            that.data.accountlist.push({
                              "goods_id": storeList[i].goods_id,
                              "quantity": storeList[i].quantity
                            })
                          }
                        }
                        var param = {
                          "longitude": app.globalData.longitude,
                          "latitude": app.globalData.latitude,
                          "address_id": that.data.addressInfo.address_id,
                          "store_id": storeId,
                          "list": that.data.accountlist,
                          "is_deliverable": e.currentTarget.dataset.isdeliverable
                        }
                        // if (parseInt(tatalPrice) >= 20) {
                        // if (param.address_id != undefined) {
                        if (that.data.accountlist.length > 0) {
                          common.showLoading("结算中...");
                          app.globalData.accountRandom = '';
                          server.postJSON(common.storePath + 'cart/check/', param, res => {
                            if (res.data.errno == "0") {
                              wx.reportAnalytics('account_cart', {
                                checklist: param.list,
                              });
                              wx.setStorage({
                                key: 'orderInfo',
                                data: res.data.data,
                                success: res => {
                                  common.hideLoading();
                                  app.globalData.isRefreshAccountList = false;
                                  wx.navigateTo({
                                    url: '../../order/pages/orderAccount?sourcetype=0',
                                  })
                                  that.setData({
                                    isAccountCart: false
                                  })
                                }
                              })
                            } else {
                              that.setData({
                                isAccountCart: false
                              })
                              common.showErrorToast(res.data.errmsg);
                            }
                          })
                        } else {
                          common.showErrorToast("请先选择商品！");
                        }
                      }
                    }
                  })
                } else {
                  common.showErrorToast(res.data.errmsg);
                }
              })
            },
            fail: res => {
              wx.removeStorage({
                key: 'userInfo',
                success: function (res) {}
              })
              this.setData({
                showLoginPop: true
              })
            }
          })
        }
      })

    },
    //前往地址管理页
    goToAddr: function (e) {
      wx.navigateTo({
        url: '../../address_manage/pages/editAddr?addrId=' + e.currentTarget.dataset.id + '&&addrType=3'
      })
      this.hideModal()
    },
    //判断按住商品是否为长按
    goToDetail(e) {
      this.setData({
        curGoodId: e.currentTarget.dataset.id,
        curStoreId: e.currentTarget.dataset.storeid
      })
      var touchTime = this.data.touch_end - this.data.touch_start;
      if (touchTime >= 350) {
        this.deleteCurGoods(e)
      }
    },
    //左滑删除商品
    delByMove(e) {
      var target = e.currentTarget.dataset
      var storeid = target.storeid,
        goodsid = target.id,
        index = target.index,
        classid = target.classid,
        quantity = target.num,
        name = target.name,
        price = target.price;
      this.setData({
        ['list.list[' + index + '].isCanReduce']: false,
        curGoodsIndex: index,
        curClassId: classid,
        curStoreId: storeid,
        curGoodId: goodsid,
        curGoodsName: name,
        curGoodsPrice: price,
        curGoodsNum: quantity,
        deleteType: 0
      })
      var param = {
        "goods": [{
          "store_id": this.data.curStoreId,
          "goods_id": this.data.curGoodId
        }],
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude
      }
      this.deleteGoods(param, this.data.curClassId);
    },
    //获取触摸屏幕开始时间及开始距离
    mytouchstart: function (e) {
      let that = this;
      that.setData({
        touch_start: e.timeStamp
      })
      if (e.touches.length == 1) {
        this.setData({
          startX: e.touches[0].clientX
        })
      }
    },
    //按下事件结束  
    mytouchend: function (e) {
      var goodsIndex = e.currentTarget.dataset.index;
      let that = this;
      that.setData({
        touch_end: e.timeStamp
      })
      var cart = this.data.list;
      var endX = e.changedTouches[0].clientX;
      var disX = this.data.startX - endX;
      var txtStyle = disX > 50 / 2 ? "left:-50px" : "left:0px";
      cart.list[goodsIndex].style = txtStyle;
      this.setData({
        list: cart
      })
    },
    //取消触摸屏幕
    touchcancel(e) {
      var cart = this.data.list,
        endX = e.changedTouches[0].clientX,
        disX = this.data.startX - endX,
        txtStyle = disX > 50 / 2 ? "left:-50px" : "left:0px",
        goodsIndex = e.currentTarget.dataset.index;
      cart.list[goodsIndex].style = txtStyle;
      this.setData({
        list: cart
      })
    },
    //左滑获取移动距离
    touchmove(e) {
      if (e.touches.length == 1) {
        var moveX = e.touches[0].clientX;
        this.setData({
          moveX: moveX
        })
      }
    },
    //修改商品数量
    updateGoodsNum(e) {
      var curtarget = e.currentTarget.dataset,
        goodnum = e.detail.value,
        storeid = curtarget.storeid,
        price = curtarget.price,
        name = curtarget.name,
        goodsid = curtarget.id,
        oldnum = curtarget.num;
      if (parseInt(goodnum) >= 1) {
        server.postJSON(common.storePath + 'cart/update/', {
          "store_id": storeid,
          "goods_id": goodsid,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "quantity": goodnum
        }, res => {
          if (res.data.errno == "0") {
            wx.reportAnalytics('addgoods_bycart', {
              goodsname: name,
              addgoodsnum: goodnum,
              removegoodsnum: goodnum,
              curgoodsnum: oldnum,
              goodsprice: price,
            });
            var goods = res.data.data;
            this.getNewCart(goods);
            if (!app.globalData.isAccount) {
              app.globalData.refreshTag = false;
            }
            var num = '',
              classid = '';
            var goodslist = goods.filter(function (item, index) {
              return item.store_id == storeid
            })
            for (var i = 0; i < goodslist[0].list.length; i++) {
              if (goodslist[0].list[i].goods_id == goodsid) {
                num = goodslist[0].list[i].quantity;
                classid = goodslist[0].list[i].category_id;
              }
            }
            this.storageUpdateGoods(storeid, goodsid, num, classid);
          } else {
            common.showErrorToast(res.data.errmsg);
            if (app.globalData.addrId == null || app.globalData.addrId == "undefined") {
              this._getCartByLonLa();
              this.setData({
                location: app.globalData.location
              })
            } else {
              var param = {
                "address_id": app.globalData.addrId,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "store_id": storeid,
                "city": app.globalData.city
              }
              this._getCartList(param);
            }

          }
        })
      } else if (parseInt(goodnum) == 0) {
        server.postJSON(common.storePath + 'cart/update/', {
          "store_id": e.currentTarget.dataset.storeid,
          "goods_id": e.currentTarget.dataset.id,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "quantity": 1
        }, res => {
          if (res.data.errno == "0") {
            wx.reportAnalytics('addgoods_bycart', {
              goodsname: name,
              addgoodsnum: 1,
              removegoodsnum: 1,
              curgoodsnum: oldnum,
              goodsprice: price,
            });
            var goods = res.data.data;
            this.getNewCart(goods);
            var num = '',
              classid = '';
            var goodslist = goods.filter(function (item, index) {
              return item.store_id == storeid
            })
            for (var i = 0; i < goodslist[0].list.length; i++) {
              if (goodslist[0].list[i].goods_id == goodsid) {
                num = goodslist[0].list[i].quantity;
                classid = goodslist[0].list[i].category_id;
              }
            }
            this.storageUpdateGoods(storeid, goodsid, num, classid);
          } else {
            common.showErrorToast(res.data.errmsg);
            if (app.globalData.addrId == null || app.globalData.addrId == "undefined") {
              this._getCartByLonLa();
              this.setData({
                location: app.globalData.location
              })
            } else {
              var param = {
                "address_id": app.globalData.addrId,
                "longitude": app.globalData.longitude,
                "latitude": app.globalData.latitude,
                "store_id": storeid,
                "city": app.globalData.city
              }
              this._getCartList(param);
            }

          }
        })
      }
    },
    //失去焦点获取商品数量
    getCurGoodsNum(e) {
      var curtarget = e.currentTarget.dataset,
        goodnum = e.detail.value,
        storeid = curtarget.storeid,
        price = curtarget.price,
        name = curtarget.name,
        goodsid = curtarget.id,
        oldnum = curtarget.num;
      if (goodnum == '') {
        server.postJSON(common.storePath + 'cart/update/', {
          "store_id": storeid,
          "goods_id": goodsid,
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "quantity": 1
        }, res => {
          if (res.data.errno == "0") {
            wx.reportAnalytics('addgoods_bycart', {
              goodsname: name,
              addgoodsnum: 1,
              removegoodsnum: 1,
              curgoodsnum: oldnum,
              goodsprice: price,
            });
            var goods = res.data.data;
            this.getNewCart(goods);
            var num = '',
              classid = '';
            var goodslist = goods.filter(function (item, index) {
              return item.store_id == storeid
            })
            for (var i = 0; i < goodslist[0].list.length; i++) {
              if (goodslist[0].list[i].goods_id == goodsid) {
                num = goodslist[0].list[i].quantity;
                classid = goodslist[0].list[i].category_id
              }
            }
            this.storageUpdateGoods(storeid, goodsid, num, classid);
          } else {
            common.showErrorToast(res.data.errmsg);
            if (app.globalData.addrId == null || app.globalData.addrId == "undefined") {
              this._getCartByLonLa();
              this.setData({
                location: app.globalData.location
              })
            } else {
              var param = {
                "address_id": app.globalData.addrId,
                "longitude": "",
                "latitude": "",
                "store_id": storeid,
                "city": app.globalData.city
              }
              this._getCartList(param);
            }
          }
        })
      }
    },
    //修改缓存中商品信息
    storageUpdateGoods(storeid, goodsid, num, classid) {
      if (storeid == this.data.curStoreId) {
        var storeArry = new Array();
        wx.getStorage({
          key: 'updateStoreArry',
          success: res => {
            storeArry = res.data;
            var t = storeArry.find(item => {
              return item.goodsid === goodsid;
            });
            if (t) {
              t.goodsnum = num;
            } else {
              storeArry.push({
                goodsid: goodsid,
                goodsnum: num,
                storeid: storeid,
                classid: classid
              })
            }
            wx.setStorage({
              key: 'updateStoreArry',
              data: storeArry,
            })
          },
          fail: res => {
            storeArry.push({
              goodsid: goodsid,
              goodsnum: num,
              storeid: storeid,
              classid: classid
            })
            wx.setStorage({
              key: 'updateStoreArry',
              data: storeArry,
            })

          }

        })
        app.globalData.isDeleteByStore = false;
      }
    },
    getRecommendGoods() {
      if (this.data.goodids.length > 0) {
        server.postJSON(common.storePath + 'store/getrecommendgoods/', {
          "store_id": this.data.curRecommendStoreId,
          "recommend_type": 'buy_to_buy',
          "recommend_num": 10,
          "goods_ids": this.data.goodids
        }, res => {
          if (res.data.errno == '0') {
            if (res.data.data.length > 0) {
              (res.data.data).forEach((item, index) => {
                item.isCanAdd = true;
                item.isCanReduce = true;
              })
              this.setData({
                recommendGoods: res.data.data
              })
              if (common.compareVersion(wx.getSystemInfoSync().SDKVersion, '1.9.6') >= 0) {
                this.data.recommendGoods.forEach((item, idx) => {
                  let intersect = wx.createIntersectionObserver();
                  intersect.relativeToViewport().observe('#easy-rec-' + item.goods_id, (res) => {
                    intersect.disconnect(); //使用disconnect，使得目标节点只曝光一次
                    console.log('曝光#easy-rec-' + item.goods_id);
                    server.postJSON(common.storePath + 'store/reportusertrace/', {
                      "store_id": this.data.curStore,
                      "recommend_type": 'buy_to_buy',
                      "list": [{
                        "goods_id": item.goods_id,
                        "trace_id": item.trace_id,
                        "position": idx
                      }]
                    }, res => {
                      if (res.data.errno == '0') {
                        console.log('曝光成功')
                      } else {
                        common.showErrorToast(res.data.errmsg)
                      }
                    })
                  })
                })
              }
            }else{
              this.setData({
                recommendGoods:[]
              })
            }
          } else {
            common.showErrorToast(res.data.errmsg)
          }
        })
      }

    },
    //添加为你推荐商品
    addRecommendCart(e) {
      var index = e.currentTarget.dataset.index;
      this.setData({
        ['recommendGoods[' + index + '].isCanAdd']: false
      })
      server.postJSON(common.storePath + 'cart/addgoods/', {
        "store_id": this.data.curStore,
        "goods_id": e.currentTarget.dataset.id,
        "trace_id": e.currentTarget.dataset.traceid,
        "scene": "buy_to_buy"
      }, res => {
        if (res.data.errno == "0") {
          common.showErrorToast('添加成功');
          this.setData({
            cartNum: parseInt(this.data.cartNum) + 1,
            ['recommendGoods[' + index + '].isCanAdd']: true,
            ['recommendGoods[' + index + '].cart_num']: parseInt(this.data.recommendGoods[index].cart_num) + 1
          })
          this._getCartByLonLa();
        } else {
          this.setData({
            ['recommendGoods[' + index + '].isCanAdd']: true
          })
          common.showErrorToast(res.data.errmsg);
        }
      })
    },
    addEmpty() {
      console.log('waiting add success')
    },
    animate() {
      var animation = wx.createAnimation({
        duration: 400,
        timingFunction: "ease-in",
        delay: 0
      })
      this.animation = animation;
      animation.translateY(500).step();
      this.setData({
        animationStoreData: animation.export(),
      })
      setTimeout(function () {
        animation.translateY(0).step()
        this.setData({
          animationStoreData: animation.export(),
          showStores: !this.data.showStores
        })
      }.bind(this), 200)
    },
    // 根据companyid拿门店数据
    showStores(e) {
      var companyid = e.currentTarget.dataset.companyid;
      var city = e.currentTarget.dataset.city;
      this.data.companyid = companyid;
      this.data.curstorecity = city;
      if(e.currentTarget.dataset.servicestoreid<=0){
        this.animate();
        server.postJSON(common.storePath + "store/search/", {
          "longitude": app.globalData.longitude,
          "latitude": app.globalData.latitude,
          "returntype": "all",
          "city": city,
          "company_id": "",
          "keyword": this.data.keyword
        }, res => {
          if (res.data.errno == '0') {
            this.setData({
              resultBuildings: res.data.data
            })
          } else {
            common.showErrorToast(res.data.errmsg);
          }
        })
      }
    },
    selectnewStore(e) {
      console.log(21)
      this.animate();
      this.data.curStore = e.currentTarget.dataset.storeid;
      var param = {
        "address_id": app.globalData.addrId,
        "longitude": "",
        "latitude": "",
        "store_id": this.data.curStore,
        "city": app.globalData.city,
        "selected": "store"
      }
      app.globalData.refreshTag=true;
      app.globalData.skipType = 2;
      this._getCartList(param);
      wx.setStorage({
        key: 'storeId',
        data: e.currentTarget.dataset.storeid,
      })
      this.setData({
        keyword: ""
      })
    },
    hideStoreModal() {
      this.animate();
      this.setData({
        keyword: ""
      })
    },
    //去推荐商品详情页
    goToProductDetail(e) {
      var curTarget = e.currentTarget.dataset;
      let goodsId = curTarget.id,
        categoryid = curTarget.categoryid;
      wx.setStorageSync('curgoodsmesg', {
        'curtraceid': curTarget.traceid,
        'curgoodsscene': this.data.classifySeletedName
      })
      app.globalData.formSceneId = '';
      wx.navigateTo({
        url: '../shop/productDetail?id=' + goodsId + '&&storeId=' + this.data.curStore + '&&categoryid=' + categoryid
      })
    },
    getKeyword(e) {
      this.setData({
        keyword: e.detail.value
      })
    },
    searchByKeyword() {
      server.postJSON(common.storePath + "store/search/", {
        "longitude": app.globalData.longitude,
        "latitude": app.globalData.latitude,
        "returntype": "all",
        "city": this.data.curstorecity,
        "company_id": "",
        "keyword": this.data.keyword
      }, res => {
        if (res.data.errno == '0') {
          this.setData({
            resultBuildings: res.data.data
          })
        } else {
          common.showErrorToast(res.data.errmsg);

        }
      })
    },
    _getCartByLonLa() {
      this.triggerEvent('getcartbylonla', this.data.curStore)
    },
    _getCartList(param) {
      this.triggerEvent('getcartlist', param)
    }
  },

})